package com.lzh.main.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lzh.main.mapper.FriendRelationMapper;
import com.lzh.main.mapper.UserMapper;
import com.lzh.main.pojo.dto.Result;
import com.lzh.main.pojo.entity.FriendRelation;
import com.lzh.main.pojo.entity.User;
import com.lzh.main.service.FriendRelationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class FriendRelationServiceImpl implements FriendRelationService {
    @Autowired
    private FriendRelationMapper friendRelationMapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    public Result sendRequest(Integer currentUserId, Integer friendId) {
        // 自检逻辑
        if (currentUserId.equals(friendId)) {
            log.warn("玩家{}尝试添加自己为好友", currentUserId);
            return Result.error("不能添加自己为好友");
        }

        // 检查目标用户是否存在
        if (userMapper.selectById(friendId) == null) {
            return Result.error("用户不存在");
        }

        // 检查是否已经是好友关系
        QueryWrapper<FriendRelation> queryWrapper = new QueryWrapper<>();
        queryWrapper
                .and(q -> q
                        .eq("user_id", currentUserId)
                        .eq("friend_id", friendId)
                        .eq("status", 1))
                .or(q -> q
                        .eq("user_id", friendId)
                        .eq("friend_id", currentUserId)
                        .eq("status", 1));

        if (friendRelationMapper.selectCount(queryWrapper) > 0) {
            return Result.error("该用户已经是你的好友");
        }

        // 3. 检查是否有未处理的PENDING请求
        QueryWrapper<FriendRelation> pendingQuery = new QueryWrapper<>();
        pendingQuery.eq("user_id", currentUserId)
                .eq("friend_id", friendId)
                .eq("status", 0);
        if (friendRelationMapper.selectOne(pendingQuery) != null) {
            return Result.error("请勿重复发送请求");
        }

        // 4. 删除旧的DECLINED记录
        QueryWrapper<FriendRelation> deleteQuery = new QueryWrapper<>();
        deleteQuery.eq("user_id", currentUserId)
                .eq("friend_id", friendId)
                .eq("status", 2);
        friendRelationMapper.delete(deleteQuery);

        // 创建新请求
        FriendRelation friendRelation = new FriendRelation();
        friendRelation.setFriendId(friendId);
        friendRelation.setUserId(currentUserId);
        friendRelation.setStatus(0);
        friendRelation.setCreateTime(new Date());
        friendRelation.setUpdateTime(new Date());
        friendRelationMapper.insert(friendRelation);

        log.info("玩家{}给玩家{}发送好友请求", currentUserId, friendId);

        return Result.success("请求已发送");
    }

    @Override
    public Result acceptRequest(Integer currentUserId, Integer friendId) {
        QueryWrapper<FriendRelation> query = new QueryWrapper<>();
        query.eq("user_id", friendId).eq("friend_id", currentUserId).eq("status", "PENDING");
        FriendRelation friendRelation = friendRelationMapper.selectOne(query);
        if (friendRelation == null) {
            return Result.error("请求不存在");
        }
        friendRelation.setStatus(1);
        friendRelation.setUpdateTime(new Date());
        friendRelationMapper.updateById(friendRelation);

        log.info("玩家{}接受玩家{}发送的好友请求", currentUserId, friendId);

        return Result.success("已接受好友请求");
    }

    @Override
    public Result declineRequest(Integer currentUserId, Integer friendId) {
        QueryWrapper<FriendRelation> query = new QueryWrapper<>();
        query.eq("user_id", friendId).eq("friend_id", currentUserId).eq("status", "PENDING");
        FriendRelation friendRelation = friendRelationMapper.selectOne(query);
        if (friendRelation == null) {
            return Result.error("请求不存在");
        }
        friendRelation.setStatus(2);
        friendRelation.setUpdateTime(new Date());
        friendRelationMapper.updateById(friendRelation);

        log.info("玩家{}拒绝玩家{}发送的好友请求", currentUserId, friendId);

        return Result.success("已拒绝好友请求");
    }

    @Override
    public Result deleteFriend(Integer userId, Integer friendId) {
        QueryWrapper<FriendRelation> query = new QueryWrapper<>();
        query.eq("user_id", userId).eq("friend_id", friendId).eq("status", 1)
                .or().eq("user_id", friendId).eq("friend_id", userId).eq("status", 1);
        if (friendRelationMapper.delete(query) > 0) {
            log.info("玩家{}删除好友{}", userId, friendId);
            return Result.success("好友删除成功");
        }

        return Result.error("好友关系不存在");
    }

    @Override
    public Result getFriendList(Integer currentUserId) {
        // 查询当前用户的所有好友关系（状态为1）
        QueryWrapper<FriendRelation> queryWrapper = new QueryWrapper<>();
        queryWrapper.and(q -> q
                        .eq("user_id", currentUserId)
                        .eq("status", 1))
                .or(q -> q
                        .eq("friend_id", currentUserId)
                        .eq("status", 1));

        List<FriendRelation> relations = friendRelationMapper.selectList(queryWrapper);

        // 提取好友ID列表
        List<Integer> friendIds = relations.stream()
                .map(relation ->
                        relation.getUserId().equals(currentUserId) ?
                                relation.getFriendId() : relation.getUserId())
                .collect(Collectors.toList());

        if (friendIds.isEmpty()) {
            return Result.success(Collections.emptyList());
        }

        // 查询好友信息并按rating降序排列
        QueryWrapper<User> userQuery = new QueryWrapper<>();
        userQuery.in("id", friendIds)
                .orderByDesc("rating");

        List<User> friends = userMapper.selectList(userQuery);

        // 脱敏处理
        List<Map<String, Object>> safeFriends = friends.stream().map(user -> {
            Map<String, Object> friendInfo = new HashMap<>();
            friendInfo.put("id", user.getId());
            friendInfo.put("username", user.getUsername());
            friendInfo.put("photo", user.getPhoto());
            friendInfo.put("level", user.getLevel());
            friendInfo.put("rating", user.getRating());
            friendInfo.put("email", user.getEmail());
            return friendInfo;
        }).collect(Collectors.toList());

        return Result.success(safeFriends);
    }

    @Override
    public Result getFriendRequests(Integer currentUserId) {
        // 查询所有发给当前用户且状态为PENDING(0)的请求
        QueryWrapper<FriendRelation> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("friend_id", currentUserId)
                .eq("status", 0)
                .orderByDesc("create_time");

        List<FriendRelation> requests = friendRelationMapper.selectList(queryWrapper);

        if (requests.isEmpty()) {
            return Result.success(Collections.emptyList());
        }

        // 获取发送者ID列表
        List<Integer> senderIds = requests.stream()
                .map(FriendRelation::getUserId)
                .collect(Collectors.toList());

        // 查询发送者信息
        QueryWrapper<User> userQuery = new QueryWrapper<>();
        userQuery.in("id", senderIds);
        List<User> senders = userMapper.selectList(userQuery);

        // 构建返回数据
        List<Map<String, Object>> result = requests.stream().map(request -> {
            Map<String, Object> requestInfo = new HashMap<>();
            requestInfo.put("id", request.getId());
            requestInfo.put("createTime", request.getCreateTime());

            // 添加发送者信息
            senders.stream()
                    .filter(sender -> sender.getId().equals(request.getUserId()))
                    .findFirst()
                    .ifPresent(sender -> {
                        requestInfo.put("senderId", sender.getId());
                        requestInfo.put("senderName", sender.getUsername());
                        requestInfo.put("senderPhoto", sender.getPhoto());
                    });

            return requestInfo;
        }).collect(Collectors.toList());

        return Result.success(result);
    }

    @Override
    public Result getFriendInfo(Integer currentUserId, Integer friendId) {
        // 1. 检查好友是否存在
        User friend = userMapper.selectById(friendId);
        if (friend == null) {
            return Result.error("用户不存在");
        }

        QueryWrapper<FriendRelation> queryWrapper = new QueryWrapper<>();
        queryWrapper.and(q -> q
                        .eq("user_id", currentUserId)
                        .eq("friend_id", friendId)
                        .eq("status", 1))
                .or(q -> q
                        .eq("user_id", friendId)
                        .eq("friend_id", currentUserId)
                        .eq("status", 1));

        if (friendRelationMapper.selectCount(queryWrapper) == 0) {
            return Result.error("该用户不是你的好友");
        }

        // 3. 返回好友信息(脱敏处理)
        Map<String, Object> friendInfo = new HashMap<>();
        friendInfo.put("id", friend.getId());
        friendInfo.put("username", friend.getUsername());
        friendInfo.put("photo", friend.getPhoto());
        friendInfo.put("level", friend.getLevel());
        friendInfo.put("rating", friend.getRating());
        friendInfo.put("email", friend.getEmail());

        return Result.success(friendInfo);
    }
}
